home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6568 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  49 lines

  1. Path: gail.ripco.com!mambuhl
  2. From: mambuhl@ripco.com (Martin Ambuhl)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: C beginner needs your
  5. Date: 19 Feb 1996 18:53:52 GMT
  6. Organization: Ripco Communications, Inc.
  7. Message-ID: <4gah00$6c6@gail.ripco.com>
  8. NNTP-Posting-Host: foley.ripco.com
  9.  
  10. sebag@ecs.umass.edu
  11. in <4g862f$p0b@risky.ecs.umass.edu> asks:
  12.  
  13. >I am a new C programmmer who desperately needs help.
  14. >I have been digging in the manuals for a way to do this but have still
  15. >come out empty handed. Here is the problem: I want to open files in a while
  16. >loop with different filenames. data0,data1,data2,data3, .. data1000 , ...
  17. >I need to increment an integer each time around then convert it to a string
  18. >and then somehow use strcat to combine the "data" with the integer string.
  19. >After that use fopen(filename, "a");
  20.  
  21. One way  -- even though it uses neither `while' nor `strcpy' -- follows.
  22. If it is necessary to use those, you should be able to figure out how to
  23. change the code:
  24.  
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27.  
  28. int main()
  29. {
  30.     char filename[FILENAME_MAX];
  31.     FILE *fp;
  32.     int i;
  33.     for (i = 0; /* continuation condition */ ; i++)
  34.     {
  35.         sprintf(filename,"data%d",i);
  36.         if (!(fp = fopen(filename,"a"))) {
  37.             fprintf(stderr,"Could not open file %s\n",filename);
  38.             exit(EXIT_FAILURE);
  39.         }
  40.         /* processing */
  41.         fclose(fp);
  42.     }
  43.     return 0;
  44. }
  45.                                
  46. --
  47. * Martin Ambuhl       net: mambuhl@ripco.com
  48. * Chicago, IL (USA)    
  49.